package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.utils.SMSUtils;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author Administrator
 * @version v1.0
 * @date 2019/10/13 21:30
 * @description TODO
 **/
@RestController
@RequestMapping("/order")
public class OrderController {

    public static final Logger log = Logger.getLogger(OrderController.class);

    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map) throws Exception {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        //验证请求的合法性，将用户提交的验证码与redis中的验证码比较
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //校验数据验证码
        if (codeInRedis == null || !codeInRedis.equalsIgnoreCase(validateCode)) {
            return Result.error(MessageConstant.VALIDATECODE_ERROR);
        }
        //将业务交给业务层处理
        map.put("orderType", Order.ORDERTYPE_WEIXIN);
        Result result = orderService.submit(map);

        if (result.isFlag()) {
        //提示用户（发短信）预约成功
            SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,"yes");
        }
        return result;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        //使用map封装数据
        try {
            Map map= orderService.findById(id);
            return Result.success(MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            log.error("Find order by id error.", e);
        }
        return Result.error(MessageConstant.QUERY_ORDER_FAIL);
    }

}